/*
 * @Author: Zhang Kai
 * @Date: 2022-05-28 02:00:32
 * @LastEditors: Zhang Kai
 * @LastEditTime: 2022-06-22 19:01:11
 * @FilePath: /metricsx-standard-ui/src/views/indexMarket/index.tsx
 */
import {
  defineComponent,
  onMounted,
  PropType,
  reactive,
  watch,
  ref,
  computed
} from 'vue';
import { ElMessage } from 'element-plus/lib/index';
import API from '@/services';
import Table from '@/components/Table/index';
import SearchForm from './searchForm';
import GroupTree from '@/components/GroupTree';
import shrinkLeft from '@/assets/images/shrinkLeft.svg';
import activeShrinkLeft from '@/assets/images/activeShrinLeft.svg';
import BatchOperates from '@/components/batchOperates/index.vue';
import Pagination from '@/components/Pagination/index';
import { useRouter } from 'vue-router';
import IndexTag from './components/indexTag/index';
import { downLoadFile } from '@/utils/http';
import { rebuildObject } from '@/utils/util';
import * as RouteNames from '@/router/consts';
import { useStore } from '@/store';
import CustomIcon from '@/components/customicon/custom-icon';
import CustomColumn from '@/components/CustomColumn/index';
import { ECustomColumn } from '@/utils/constants';
import qs from 'qs';
import _ from 'lodash';
import './index.scss';
const indexMarket = defineComponent({
  name: 'indexMarket',
  // props: {},
  setup: (props, { slots, attrs, emit }) => {
    // 获取api
    const {
      metricsGroup: { getMetricsGroupListRoot, getMetricsGroupRootByRootId }
    } = API;

    const indexMarketList: any = reactive({
      list: [],
      total: 0,
      pageNum: 1,
      pageSize: 12,
      order: undefined,
      sortBy: undefined
    });

    /* 收缩状态 */
    const toggle = ref(false);

    const router = useRouter();

    const shrinkIcon = ref(shrinkLeft);

    // 分组key
    const groupKey = ref(1);

    const formQuery = reactive({ form: { groupId: '', rootId: '' } });

    // 选择row
    const multipleSelection: any = reactive({ data: [] });

    const store = useStore();

    const visible = computed(() => store.state.indexlibrary.drawerVisible);

    const TableLoading = ref(false);

    /* 自定义列表 */
    const settings = ref([]);

    /* 分类节点列表 */
    const ClassfiyList: any = ref([]);

    /* 选中的视图 */
    const activeView = ref('card');

    const toggleViewList = ref([
      { command: 'card', text: '卡片视图3N' },
      { command: 'list', text: '列表视图' }
    ]);

    /* column */
    const newTableColumn = ref([]);

    /* 标签list key */
    const tagListKey = ref(1);

    /* table Column */
    const tableColumn: any = ref([
      {
        label: '名称',
        default: ({ row }: any) => (
          <a
            class="cnName"
            onClick={() =>
              router.push({
                name: RouteNames.ROUTE_INDEXDETAIL,
                query: { id: row.id }
              })
            }
          >
            {row.cnName}
          </a>
        ),
        keys: 2
      },
      {
        keys: 1,
        sortable: true
      },
      {
        keys: 8,
        sortable: true
      },
      {
        keys: 11,
        sortable: true
      },
      {
        label: '操作',
        keys: 14,
        default: ({ row }: any) => {
          return (
            <>
              <el-button onClick={() => exports(row.id)} type="text">
                导出
              </el-button>
              <el-button
                type="text"
                onClick={(e: any) => {
                  e.preventDefault();
                  toggleFavoriteStatus(row);
                }}
              >
                {row.favoriteStatus ? '取消收藏' : '收藏'}
              </el-button>
            </>
          );
        }
      }
    ]);

    /* 更多操作 */
    const handleBatchOperate = async (v: any) => {
      if (multipleSelection.data.length === 0) {
        ElMessage.warning('请勾选操作项，再进行批量操作');
        return false;
      }
      let code, data;
      const ids = multipleSelection.data.map((d: any) => d.id);
      switch (v) {
        case 'collection':
          ({ code, data } =
            await API.favoriteMetrics.postFavoriteMetricsBatchCreate({ ids }));
          if (code === 200) {
            ElMessage.success('批量收藏成功');
          }
          indexMarketList.pageNum = 1;
          getIndexMarketList();
          break;
        case 'cancel-collection':
          ({ code, data } =
            await API.favoriteMetrics.deleteFavoriteMetricsBatchCancel({
              ids
            }));
          if (code === 200) {
            ElMessage.success('批量取消收藏成功');
          }
          indexMarketList.pageNum = 1;
          getIndexMarketList();
          break;
        case 'export':
          exports(ids);
          break;
      }
    };

    /* 导出 */
    const exports = (ids: any) => {
      try {
        downLoadFile({
          url: '/metrics/library/batch-export',
          method: 'get',
          params: { ids: ids },
          config: {
            paramsSerializer: function (params: any) {
              return qs.stringify(params, { indices: false }); // param=value1&param=value2
            }
          }
        });
      } catch (error) {
        console.log(error);
      }
    };

    /* 列表 */
    const getIndexMarketList = async () => {
      TableLoading.value = true;
      try {
        const { pageNum, pageSize } = indexMarketList;
        const { code, data }: any = await API.metrics.getMetricsList({
          pageSize,
          pageNum,
          reviewStatus: 5,
          ...rebuildObject(formQuery.form)
        });
        if (code === 200 && Array.isArray(data?.list)) {
          indexMarketList.list = [...data?.list];
          indexMarketList.total = +data?.total;
          multipleSelection.data = [];
          tagListKey.value++;
        }
      } catch (error) {
        console.log(
          '🚀 ~ file: index.tsx ~ line 118 ~ indexMarketList ~ error',
          error
        );
      } finally {
        TableLoading.value = false;
      }
    };

    /* 分类节点列表 */
    const getClassfiyList = async () => {
      try {
        let { code, data } = await getMetricsGroupListRoot({
          display: 1,
          pageNum: 1,
          pageSize: 50
        });
        if (code === 200 && Array.isArray(data?.list)) {
          ClassfiyList.value = data?.list;
        }
      } catch (error) {
        console.log(error);
      }
    };

    /* 排序 */
    const sortTable = (obj: any) => {
      if (obj.prop) {
        const order = obj.order === 'ascending' ? 1 : 2;
        indexMarketList.sortBy = obj.prop;
        indexMarketList.order = order;
      } else {
        indexMarketList.sortBy = undefined;
        indexMarketList.order = undefined;
      }
      getIndexMarketList();
    };

    //收藏状态
    const toggleFavoriteStatus = async (row: any) => {
      if (row) {
        const { favoriteStatus, id } = row;
        if (favoriteStatus === 1) {
          // 取消
          const { code } = await API.favoriteMetrics.putFavoriteMetricsById({
            id
          });
          if (code === 200) {
            getIndexMarketList();
            ElMessage.success('取消收藏成功');
          } else {
            ElMessage.error('取消收藏失败');
          }
        } else {
          //添加
          const { code } = await API.favoriteMetrics.getFavoriteMetricsById({
            id
          });
          if (code === 200) {
            getIndexMarketList();
            ElMessage.success('收藏成功');
          } else {
            ElMessage.error('收藏失败');
          }
        }
      }
    };

    /* 获取自定义列列表 */
    const getCustomColumnApi = async () => {
      try {
        const { code, data }: any = await API.userPageSetting.getFindOne({
          pageCode: ECustomColumn?.indexlib
        });
        if (code === 200) {
          settings.value = data?.settings;
          const column = data?.settings?.map((v: any, i: number) => {
            const columnIndex = tableColumn.value?.findIndex(
              (val: any) => val?.keys === v?.keys
            );
            return {
              ...tableColumn.value[columnIndex],
              ...v,
              columnKey: Date.now()
            };
          });
          column.unshift({
            type: 'selection',
            width: '55',
            isCheck: true
          });
          newTableColumn.value = _.compact(column);
        }
      } catch (error) {
        console.log(error);
      }
    };

    /* 保存自定义列表 */
    const customColumnConfirm = async (vo: any) => {
      try {
        const { code } = await API.userPageSetting.postSave({
          pageCode: ECustomColumn?.indexlib,
          settings: vo?.map(({ disabled, keys, isCheck, label, prop }: any) => {
            return {
              disabled,
              keys,
              isCheck,
              label,
              prop
            };
          })
        });
        if (code === 200) {
          ElMessage.success('保存配置成功');
          getCustomColumnApi();
        }
      } catch (error) {
        console.log(error);
      }
    };

    watch(
      () => visible.value,
      (bol) => {
        !bol && getIndexMarketList();
      }
    );

    onMounted(() => {
      getIndexMarketList();
      getClassfiyList();
      getCustomColumnApi();
    });

    return () => {
      return (
        <div class="indexMarket-container">
          <div
            class="indexMarket-left"
            style={{ width: toggle.value ? '0px' : '210px' }}
          >
            <img
              class={toggle.value && 'shrinkRight'}
              onClick={() => (toggle.value = !toggle.value)}
              src={shrinkIcon.value}
              onMouseenter={() => (shrinkIcon.value = activeShrinkLeft)}
              onMouseout={() => (shrinkIcon.value = shrinkLeft)}
              alt=""
            />
            <div class="ClassfiyList-container">
              <div class="ClassfiyList-title">指标分类管理</div>
              <div class="ClassfiyList-group-container">
                {ClassfiyList.value.map((v: any) => (
                  <GroupTree
                    activeCurrent={false}
                    isTitles={false}
                    isOperate={false}
                    groupId={formQuery.form.groupId}
                    groupKey={groupKey.value}
                    listFn={() => getMetricsGroupRootByRootId({ rootId: v.id })}
                    onGetTreeNode={({ id, rootId }: any) => {
                      if (id === 'new') return;
                      formQuery.form.groupId = id;
                      formQuery.form.rootId = rootId;
                      indexMarketList.pageNum = 1;
                      getIndexMarketList();
                    }}
                  ></GroupTree>
                ))}
              </div>
            </div>
          </div>
          <div class="indexMarket-right">
            <SearchForm
              onSearch={(form: any) => {
                indexMarketList.pageNum = 1;
                indexMarketList.pageSize = 12;
                formQuery.form = form;
                formQuery.form.groupId = '';
                formQuery.form.rootId = '';
                getIndexMarketList();
              }}
            />
            <div class="table-operate">
              <div class="CustomColumn-operate-wrap">
                {activeView.value === 'list' && (
                  <CustomColumn
                    onConfirm={(v: any) => customColumnConfirm(v)}
                    tableColumn={settings.value}
                  />
                )}

                <div class="checkLength">
                  已选择<b>{multipleSelection.data.length}</b>个指标
                </div>
              </div>
              <div class="batch-operate-wrap">
                <el-dropdown
                  trigger="click"
                  onCommand={(code: any) => {
                    activeView.value = code;
                    indexMarketList.pageSize = code === 'list' ? 10 : 12;
                    getIndexMarketList();
                  }}
                  v-slots={{
                    dropdown: () => (
                      <el-dropdown-menu>
                        {toggleViewList.value?.map((v: any) => (
                          <el-dropdown-item {...v}>{v.text}</el-dropdown-item>
                        ))}
                      </el-dropdown-menu>
                    )
                  }}
                >
                  <div class="toggleView-container">
                    <el-button>
                      <CustomIcon
                        onClick={() => emit('collection')}
                        name="icon-metricsx-a-kapianshitucardview"
                      />
                      切换视图
                    </el-button>
                  </div>
                </el-dropdown>
                <BatchOperates
                  v-loading={TableLoading.value}
                  opKeys={['collection', 'cancel-collection', 'export']}
                  onBatchOperate={handleBatchOperate}
                  disabled={multipleSelection.data.length === 0}
                />
              </div>
            </div>
            {activeView.value === 'card' ? (
              <div
                class="indexTagList-container"
                key={tagListKey.value}
                v-loading={TableLoading.value}
              >
                <div class="indexTagList-container-content">
                  {indexMarketList.list?.map((v: any) => (
                    <IndexTag
                      onClick={() => {
                        router.push({
                          name: RouteNames.ROUTE_INDEXDETAIL,
                          query: { id: v.id }
                        });
                      }}
                      onCollection={() => toggleFavoriteStatus(v)}
                      onExports={() => exports(v.id)}
                      onCheck={() => {
                        const index = multipleSelection.data.findIndex(
                          (j: any) => j.id === v.id
                        );
                        if (index === -1) {
                          multipleSelection.data.push(v);
                        } else {
                          multipleSelection.data.splice(index, 1);
                        }
                      }}
                      info={v}
                    />
                  ))}
                </div>
                <Pagination
                  onCurrentChange={(page: number) => {
                    indexMarketList.pageNum = page;
                    getIndexMarketList();
                  }}
                  onSizeChange={(size: number) => {
                    indexMarketList.pageNum = 1;
                    indexMarketList.pageSize = size;
                    getIndexMarketList();
                  }}
                  currentPage={indexMarketList.pageNum}
                  pageSize={indexMarketList.pageSize}
                  pageSizes={[12, 24, 36, 48]}
                  total={indexMarketList.total}
                />
              </div>
            ) : activeView.value === 'list' ? (
              <Table
                showCheckbox={true}
                v-loading={TableLoading.value}
                onSortChange={sortTable}
                data={indexMarketList.list}
                column={newTableColumn.value.filter((v: any) => v.isCheck)}
                onSelectionChange={(v: any) => (multipleSelection.data = v)}
                onPageCurrentChange={(page: number) => {
                  indexMarketList.pageNum = page;
                  getIndexMarketList();
                }}
                onPageSizeChange={(size: number) => {
                  indexMarketList.pageNum = 1;
                  indexMarketList.pageSize = size;
                  getIndexMarketList();
                }}
                pagination={{
                  total: indexMarketList.total,
                  currentPage: indexMarketList.pageNum,
                  pageSize: indexMarketList.pageSize
                }}
              />
            ) : undefined}
          </div>
        </div>
      );
    };
  }
});

export default indexMarket;
